//
// Created by tanke on 23-11-27.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Item
{
    size_t len;
    char* str;
};

char* reverseWords(char* s)
{
    size_t wordStartPos = 0;
    size_t wordEndPos = 0;
    struct Item wordStack[10000];
    int wordStackLen = 0;
    char* result = (char*)malloc(sizeof(char) * (strlen(s) + 1));
    size_t index = 0;

    memset(result, 0, sizeof(char) * (strlen(s) + 1));

    for (size_t i = 0; i < strlen(s); i ++) {
        if (s[i] == ' ') {
            if (i == 0) {
                continue;
            } else {
                if (s[i-1] == ' ') {
                    continue;
                } else {
                    wordEndPos = i;
                    wordStack[wordStackLen].len = wordEndPos - wordStartPos;
                    wordStack[wordStackLen].str = (char*)malloc(sizeof(char) * wordStack[wordStackLen].len);
                    memcpy(wordStack[wordStackLen].str, s + wordStartPos, wordStack[wordStackLen].len);
                    wordStackLen += 1;
                }
            }
        } else {
            if (i == 0) {
                wordStartPos = i;
            } else {
                if (s[i - 1] == ' ') {
                    wordStartPos = i;
                }
            }
        }
    }
#if 0
    printf("%d %d\n", wordStartPos, wordEndPos);
#endif
    if (wordEndPos <= wordStartPos) {
        wordEndPos = strlen(s);
        wordStack[wordStackLen].len = wordEndPos - wordStartPos;
        wordStack[wordStackLen].str = (char*)malloc(sizeof(char) * wordStack[wordStackLen].len);
        memcpy(wordStack[wordStackLen].str, s + wordStartPos, wordStack[wordStackLen].len);
        wordStackLen += 1;
    }

    for (int i = wordStackLen - 1; i > 0; i --) {
        memcpy(result + index, wordStack[i].str, wordStack[i].len);
        index += wordStack[i].len;
        result[index] = ' ';
        index += 1;
    }

    memcpy(result + index, wordStack[0].str, wordStack[0].len);

    return result;
}

int main(void)
{
    const char* s = "EPY2giL";
    printf("%s\n", reverseWords(s));

    return 0;
}